﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using WXApi.Model;
using WxTenpay.Service.Model;
using WxTenpay.Service;

namespace WXApi.Controllers
{
    /// <summary>
    ///角色数据接口
    /// </summary>
    [Route("[controller]/[action]")]
    [ApiController]
    [Action]
    public class SysRoleController : ReqDataControllerBase
    {
        private readonly ISysRoleAuthorization _isysroleauthorization;
        private readonly ISysRole _isysrole;
        private readonly ISysMenu sysmenu;
        private readonly ISysMenuButton sysmenubutton;
        private readonly ISysLog syslog;
        private readonly ISysLoginLog sysloginlog;
        public SysRoleController(ISysLog _syslog, ISysLoginLog _sysloginlog, ISysMenu _sysmenu, ISysMenuButton _sysmenubutton, ISysRoleAuthorization isysroleauthorization, ISysRole isysrole)
        {
            syslog = _syslog;
            _isysroleauthorization = isysroleauthorization;
            _isysrole = isysrole;
            sysmenu = _sysmenu;
            sysmenubutton = _sysmenubutton;
            sysloginlog = _sysloginlog;
        }


        #region 权限管理
        /// <summary>
        /// 获取用户菜单数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetRoleMenu(string gid)
        {
            try
            {
                var token = HttpContext.Items["token"].ToString();
                //登入账号信息
                var userguid = GetUser(token);
                var btnlis = sysmenubutton.GetList();
                var list = sysmenu.GetList().Select(x =>
                {
                    x.buttons = btnlis.Where(p => p.MenuGuId == x.GuId).ToList();
                    return x;
                }).ToList();


                //获取当前角色的信息
                var usermodel = _isysrole.GetModel(x => x.GuId == gid);
                if (usermodel == null)
                    return Error("参数异常！");

                List<SysRoleAuthorizationEntity> userRoleAuthorization = new List<SysRoleAuthorizationEntity>();
                userRoleAuthorization = _isysroleauthorization.GetList(x => x.UserGid == gid);
                var rdata = new
                {
                    list,
                    userRoleAuthorization = userRoleAuthorization.Select(x =>
                    {
                        return new
                        {
                            x.MenuGid,
                            x.ButtonLis,
                            x.UserGid
                        };
                    })
                };

                return Success(rdata);
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysRole/GetRoleMenu", Content = ex.ToString(), Name = "获取用户菜单数据" };
                return ErrorLog(model);
            }
        }
        #endregion

        #region

        /// <summary>
        /// 获取用户列表信息 
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult GetRoleList([FromBody] PageModel.PageParm parm)
        {
            try
            {
                var data = _isysrole.GetRolePages(parm);
                return Success(data);
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysRole/GetRoleList", Content = ex.ToString(), Name = "获取用户列表信息" };
                return ErrorLog(model);

            }
        }


        /// <summary>
        /// 新增角色 
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult AddRole([FromBody] SysRoleEntity entity)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(entity.GuId))
                {     //新增

                    if (_isysrole.GetModel(x => x.Name == entity.Name) != null)
                    {
                        entity.Create();

                        _isysrole.Add(entity);

                        SuccessLogDto loginmodel = new SuccessLogDto();
                        loginmodel.data = "操作成功";
                        loginmodel._sysloginlog = sysloginlog;
                        loginmodel.loginlogmodel = new SysLoginLogEntity { Type = 1, Content = "新增角色信息" };
                        return SuccessLog(loginmodel);

                    }
                    else
                        return Error("对不起您的角色已存在！");
                }
                else
                {   //修改信息
                    var model = _isysrole.GetModel(x => x.GuId == entity.GuId);
                    if (model != null)
                    {
                        model.Name = entity.Name;
                        model.Number = entity.Number;
                        model.Remark = entity.Remark;

                        _isysrole.Update(model);
                    }

                    SuccessLogDto loginmodel = new SuccessLogDto();
                    loginmodel.data = "操作成功";
                    loginmodel._sysloginlog = sysloginlog;
                    loginmodel.loginlogmodel = new SysLoginLogEntity { Type = 2, Content = "修改角色信息" };
                    return SuccessLog(loginmodel);
                }

       
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysRole/AddRole", Content = ex.ToString(), Name = "新增角色" };
                return ErrorLog(model);
            }
        }



        /// <summary>
        /// 修改用户权限 
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult ModifyPermissions([FromBody] List<SysRoleAuthorizationEntity> lis, [FromQuery] string gid)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(gid)) return Error("参数异常！");

                using (TransactionScope tran = new TransactionScope())
                {
                    int count = _isysroleauthorization.Delete(x => x.UserGid == gid);

                    lis.ForEach(x =>
                    {
                        x.Create();
                        x.UserGid = gid;
                        x.Type = 1;
                        _isysroleauthorization.Add(x);
                    });
                    tran.Complete();
                }
                SuccessLogDto loginmodel = new SuccessLogDto();
                loginmodel.data = "操作成功";
                loginmodel._sysloginlog = sysloginlog;
                loginmodel.loginlogmodel = new SysLoginLogEntity { Type = 1, Content = "修改用户权限" };
                return SuccessLog(loginmodel);

            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysRole/ModifyPermissions", Content = ex.ToString(), Name = "修改角色权限" };
                return ErrorLog(model);
            }
        }






        /// <summary>
        /// 获取菜单列表数据
        /// </summary>
        /// <param name="lis"></param>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        private object getmenu(List<SysMenuEntity> lis, List<SysMenuButtonEntity> btnlis, string ParentId = "0")
        {
            try
            {
                var list = lis.Where(x => x.ParentId == ParentId).Select(x =>
                {
                    return new
                    {
                        Id = x.Id,
                        GuId = x.GuId,
                        Icon = x.Icon,
                        Name = x.Name,
                        Type = x.Type,
                        Address = x.Address,
                        Sort = x.Sort,
                        ParentId = x.ParentId,
                        Btnlis = btnlis.Where(p => p.MenuGuId == x.GuId),
                        children = getmenu(lis, btnlis, x.Id.ToString())
                    };


                });

                return list;

            }
            catch (Exception)
            {

                throw;
            }

        }






        #endregion






    }
}
